<template>
  <div class="addlist">
    <scroll-view
      class="cel"
      scroll-y="true"
      :style="{background:background}"
      lower-threshold="20"
      bindscrolltolower="getAddressList"
    >
      <div class="main">
        <block v-for="(item,index) in dataList" :key="index">
          <div class="item">
            <div class="head" :data-id="item.id" @click="selectAddress(item.id)">
              <div class="h">
                <div class="username">{{item.consignee}}</div>
                <div class="mobile">{{item.mobile}}</div>
              </div>
              <div>
                <div class="b">
                  <van-tag class="vtag" :data-status="item.is_default" v-if="item.is_default" color="#ffe1e1" text-color="#ad0000">默认</van-tag> 
                  {{item.province_str}} {{item.city_str}} {{item.district_str}} {{item.address}}
                </div>
              </div>
            </div>
            <div class="editAR">
              <div class="edit" @click="editAddress(item.id,index)" > 编辑 </div>
            </div>
          </div>
          <div style="width:100%;height:16px;background:#F8F8F8"></div>
        </block>
        <div v-if="dataList.length<1">
          <div class="news-bottom">
            <div class="news-no">您还没有建立收货地址</div>
          </div>
        </div>
      </div>
    </scroll-view>
    <!-- <navigator url='/pages/my/address/add'> -->
    <button size="large" class="add" @click="addnew">新增收货地址</button>
    <!-- </navigator> -->
    <van-dialog
      zIndex="100"
      use-slot
      async-close
      :show="add_status"
      show-cancel-button
      confirm-button-open-type="add"
      @cancel="closeAdd"
      @confirm="confirmAdd"
      :add="add"
    >
      <div class="body">
      <form bindsubmit="formSubmit">
        <div class="main dialog">
          <input class="list" name="name" placeholder="姓名" :value="username" @input="bindName">
          <input class="list" name="phone" type="number" @blur="validatePhone" maxlength="11" placeholder="手机号" :value="mobile" @input="bindphone">
          <picker
            @change="onConfirm"
            @cancel="regionCancel"
            @columnchange="bindCityColumnChange"
            mode="multiSelector"
            :value="multiIndex"
            :range="multiArray" 
            range-key="name"
          >
            <input
              disabled="true"
              class="list"
              name="address"
              :value="regioninfo"
              placeholder="省份 城市 区县"
            >
          </picker>
          <input class="list" name="detail" placeholder="详细地址、如街道、楼牌号等" :value="address" @input="bindaddress">
          <div class="mzTt">
            <label for="">设为默认地址</label> 
            <van-switch
              class="mzTtBox"
              size="35rpx"
              :checked="is_default"
              @change="onChange"
              active-color="#62b976"
              inactive-color="#fff"
            />
          </div>
          <div class="mzTt" v-if="del_status">
            <label for="">删除该地址</label> 
            <van-button class="mzTtBox" type="danger" size="mini" @click="swipeBlock"> 删除 </van-button>
          </div>
        </div>
      </form>
    </div>
    </van-dialog>
    <van-dialog id="van-dialog" zIndex="999"/>
    <van-toast id="van-toast" />
  </div>
</template>
<script>
import Dialog from '../../../static/vant/dialog/dialog'
import Toast from '../../../static/vant/toast/toast'
import { integral, views, validatePhone } from '../../utils/utils.js'
import Vue from 'vue'
export default {
  onShareAppMessage (res) {
    if (res.from === 'button') {
      // 增加积分
      this.sharpePage(this.$root.$mp.query.id, 3)
    } else {
      this.sharpePage(this.$root.$mp.query.id, 4)
    }
    return {
      title: '收货地址',
      imageUrl: '/images/a.png',
      path: '/pages/address/main'
    }
  },
  onShow () {
    let _this = this
    this.userDtr = wx.getStorageSync('userDtr')
    this.inputType = this.$root.$mp.query.type
    // 获取收货地址列表
    wx.request({
      url: this.apiUrl + 'api/address?uid_str=' + this.userDtr,
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: res => {
        console.log(res)
        let data = res.data
        if (data.code === 200) {
          _this.dataList = data.data
        }
      },
      fail: (e) => {},
      complete: () => {}
    })
  },
  data () {
    return {
      dataList: [],
      del_status: false,
      add_status: false, // 地址弹窗
      id: 0,
      background: '#ffffff',
      enter: 0,
      page: 1,
      more: false,
      checked: '',
      region: [],
      regioninfo: [], /* 省市区显示 */
      address_id: '',
      username: '',
      mobile: '',
      address: '',
      is_default: false,
      editIndex: '',
      editMode: false,
      multiArray: [[{
        id: 7460,
        pid: 0,
        name: '北京'
      }], [{
        id: 7461,
        pid: 7460,
        name: '北京市'
      }], []],
      multiIndex: [0, 0, 0],
      userDtr: '',
      inputType: ''
    }
  },
  components: {},
  methods: {
    // 积分增加， 更新 分享、浏览 、转发数量，增加积分
    // type:share 更新分享数   views  更新浏览数 forwarding 更新转发数
    getIntegral (type = 2) {
      let _this = this
      let id = _this.$root.$mp.query.id
      // 增加积分
      integral(id, type)
      // 增加统计数量  views
      views(id, 'views')
    },
    // 1.签到 2.阅读文章 3.转发文章 4.分享小程序
    sharpePage (id, type = 3) {
      // 增加积分
      integral(id, type)
      // 增加统计数量 share
      views(id, 'share')
    },
    // 从订单页面过来的返回订单页面
    selectAddress (id) {
      console.log(this.inputType)
      if (this.inputType === 'order') {
        wx.navigateTo({ url: '/pages/order/main?addressId=' + id })
      } else {
        console.log('没有inputType值')
      }
    },
    // 绑定姓名
    bindName (event) {
      this.username = event.mp.detail.value
    },
    // 绑定手机号
    bindphone (event) {
      this.mobile = event.mp.detail.value
    },
    // 绑定地址
    bindaddress (event) {
      this.address = event.mp.detail.value
    },
    // 新增收货 按钮点击
    addnew () {
      this.address_id = ''
      this.add_status = true
      this.del_status = false
      this.username = ''
      this.mobile = ''
      this.address = ''
      this.is_default = 0
      this.editMode = false
    },
    // 弹窗确认
    confirmAdd (e) {
      // 校测手机号格式
      if (!validatePhone(this.mobile)) {
        Toast('手机号格式不正确!')
      } else {
        let _this = this
        if (this.editMode) {
          // 更新地址
          wx.request({
            url: _this.apiUrl + 'api/address/update',
            data: {
              'address_id': _this.address_id,
              'uid_str': _this.userDtr,
              'province': _this.region[0],
              'city': _this.region[1],
              'district': _this.region[2],
              'consignee': _this.username,
              'address': _this.address,
              'mobile': _this.mobile,
              'is_default': _this.is_default
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            method: 'POST',
            dataType: 'json',
            success: res => {
              console.log(res)
              let data = res.data
              if (data.code === 200) {
                if (_this.regioninfo.length === 3) {
                  let itemLen = _this.editIndex
                  if (_this.is_default) {
                    _this.dataList.forEach(element => {
                      element.is_default = 0
                    })
                  }
                  _this.address_id = data.data.address_id
                  Vue.set(_this.dataList[itemLen], 'consignee', _this.username)
                  Vue.set(_this.dataList[itemLen], 'mobile', _this.mobile)
                  Vue.set(_this.dataList[itemLen], 'address', _this.address)
                  Vue.set(_this.dataList[itemLen], 'province', _this.region[0])
                  Vue.set(_this.dataList[itemLen], 'city', _this.region[1])
                  Vue.set(_this.dataList[itemLen], 'district', _this.region[2])
                  Vue.set(_this.dataList[itemLen], 'is_default', _this.is_default)
                } else {
                  wx.showToast({
                    title: '请选择收货地址！',
                    icon: 'none',
                    duration: 2000
                  })
                }
              }
            },
            fail: () => {},
            complete: () => {}
          })
        } else {
          if (_this.region.length === 3) {
            // 添加地址
            wx.request({
              url: _this.apiUrl + 'api/address/add',
              data: {
                'uid_str': _this.userDtr,
                'province': _this.region[0],
                'city': _this.region[1],
                'district': _this.region[2],
                'consignee': _this.username,
                'address': _this.address,
                'mobile': _this.mobile,
                'is_default': _this.is_default
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              method: 'POST',
              dataType: 'json',
              success: res => {
                console.log(res)
                let data = res.data
                if (data.code === 200) {
                  if (_this.regioninfo.length === 3) {
                    if (_this.is_default) {
                      _this.dataList.forEach(element => {
                        element.is_default = 0
                      })
                    }
                    _this.address_id = data.data.address_id
                    _this.dataList.push({
                      'id': data.data.address_id,
                      'province': _this.region[0],
                      'city': _this.region[1],
                      'district': _this.region[2],
                      'consignee': _this.username,
                      'address': _this.address,
                      'mobile': _this.mobile,
                      'is_default': _this.is_default,
                      'province_str': _this.regioninfo[0],
                      'city_str': _this.regioninfo[1],
                      'district_str': _this.regioninfo[2]
                    })
                  }
                }
              },
              fail: () => {},
              complete: () => {}
            })
          }
        }
        this.add_status = false
      }
    },
    // 弹窗取消
    closeAdd () {
      this.add_status = false
      this.del_status = false
      this.editMode = false
      this.regioninfo = []
      this.region = []
    },
    // 确认城市选择
    onConfirm (event) {
      console.log(event.mp.detail.value)
      let arr = event.mp.detail.value
      if (arr.length === 3) {
        Vue.set(this.region, [0], this.multiArray[0][arr[0]].id)
        Vue.set(this.region, [1], this.multiArray[1][arr[1]].id)
        Vue.set(this.region, [2], this.multiArray[2][arr[2]].id)
        Vue.set(this.regioninfo, [0], this.multiArray[0][arr[0]].name)
        Vue.set(this.regioninfo, [1], this.multiArray[1][arr[1]].name)
        Vue.set(this.regioninfo, [2], this.multiArray[2][arr[2]].name)
        // console.log(this.regioninfo)
        // console.log(this.region)
      }
    },
    // 选择地址三列
    bindCityColumnChange (event) {
      let pid = this.multiArray[0][event.mp.detail.value].id
      switch (event.mp.detail.column) {
        case 0:
          wx.request({
            url: this.apiUrl + 'api/area?province=' + pid,
            success: res => {
              let data = res.data
              if (data.code === 200) {
                var temp = data.data
                Vue.set(this.multiIndex, [0], event.mp.detail.value)
                this.multiArray[1] = Object.assign([], temp)
                // 默认二级索引为 0 数据填充二级，请求三级数据
                // console.log(this.multiArray[1][0])
                let ctid = this.multiArray[1][0].id
                wx.request({
                  url: this.apiUrl + 'api/area?city=' + ctid,
                  success: rest => {
                    // console.log(rest)
                    let data = rest.data
                    var temps = data.data
                    Vue.set(this.multiIndex, [1], 0)
                    this.multiArray[2] = Object.assign([], temps)
                  },
                  fail: () => {},
                  complete: () => {}
                })
              }
            },
            fail: () => {},
            complete: () => {}
          })
          break
        case 1:
          Vue.set(this.multiIndex, [1], event.mp.detail.value)
          // console.log(event.mp.detail.value)
          let cid = this.multiArray[1][event.mp.detail.value].id
          wx.request({
            url: this.apiUrl + 'api/area?city=' + cid,
            success: rest => {
              // console.log(rest)
              let data = rest.data
              var temps = data.data
              Vue.set(this.multiIndex, [2], 0)
              this.multiArray[2] = Object.assign([], temps)
            },
            fail: () => {},
            complete: () => {}
          })
          break
        case 2:
          Vue.set(this.multiIndex, [2], event.mp.detail.value)
          break
        default:
          break
      }
    },
    // 取消城市选择
    regionCancel () {
      console.log('取消')
    },
    // 修改默认地址
    onChange (event) {
      this.is_default = !this.is_default
    },
    // 编辑 按钮
    editAddress (id, index) {
      this.address_id = id
      this.add_status = true
      this.del_status = true
      this.username = this.dataList[index].consignee
      this.mobile = this.dataList[index].mobile
      this.address = this.dataList[index].address
      this.is_default = this.dataList[index].is_default
      this.editIndex = index
      this.editMode = true
      Vue.set(this.regioninfo, [0], this.dataList[index].province_str)
      Vue.set(this.regioninfo, [1], this.dataList[index].city_str)
      Vue.set(this.regioninfo, [2], this.dataList[index].district_str)
      Vue.set(this.region, [0], this.dataList[index].province)
      Vue.set(this.region, [1], this.dataList[index].city)
      Vue.set(this.region, [2], this.dataList[index].district)
    },
    // 删除地址
    swipeBlock (event) {
      console.log(event)
      let _this = this
      let userDtr = wx.getStorageSync('userDtr')
      Dialog.confirm({
        message: '确定删除吗？'
      }).then(() => {
        wx.request({
          url: this.apiUrl + 'api/address/del',
          data: {
            'uid_str': userDtr,
            'address_id': _this.address_id
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          method: 'post',
          dataType: 'json',
          success: res => {
            _this.add_status = false
            _this.dataList.splice(_this.editIndex, 1)
          },
          fail: () => {},
          complete: () => {}
        })
      })
    }
  },
  mounted () {
    let _this = this
    // 获取省份
    wx.request({
      url: _this.apiUrl + 'api/area',
      success: res => {
        let data = res.data
        if (data.code === 200) {
          var temp = data.data
          _this.multiArray[0] = Object.assign([], temp)
        }
      },
      fail: () => {},
      complete: () => {}
    })
    // 获取城市
    wx.request({
      url: this.apiUrl + 'api/area?province=7460',
      success: res => {
        let data = res.data
        if (data.code === 200) {
          var temp = data.data
          this.multiArray[1] = Object.assign([], temp)
        }
      },
      fail: () => {},
      complete: () => {}
    })
    // 获取地区
    wx.request({
      url: this.apiUrl + 'api/area?city=7461',
      success: res => {
        let data = res.data
        if (data.code === 200) {
          var temp = data.data
          this.multiArray[2] = Object.assign([], temp)
        }
      },
      fail: () => {},
      complete: () => {}
    })
  }
}
</script>
<style scoped>
.mzTt {
  width: 100%;
  height: 50px;
  line-height: 50px;
  background: #ffffff;
  border-top: 1px solid #f8f8f8;
  font-size: 13px;
  display: block;
}
.mzTt label {
  width: 80%;
  display: inline-block;
}
.mzTtBox {
  width: 20%;
  display: inline-block;
  text-align: center;
}
.address {
  width: 100%;
  display: inline-block;
}
.edit {
  width: 100%;
  display: inline-block;
  font-size: 14px;
  text-align: center;
  color: #999;
  border-left:1px solid #eee;
  padding: 5px 0;
  position:relative;
  top:-50%;
}
.addlist {
  height:calc(100vh - 130rpx);
}
.add {
  width: 60%;
  height: 80rpx;
  background: #62b976;
  border-radius: 10rpx;
  color: #ffffff;
  font-size: 16px;
  line-height: 80rpx;
  text-align: center;
  margin: 0 auto;
  margin-top: 20rpx;
  position:absolute;
  bottom:15px;
  left:50%;
  margin-left:-110px;
}
.empty {
  background: #f8f8f8;
}
.cel {
  height:calc(100vh - 130rpx);
}
.body .main {
  width: 100%;
  height: auto;
  font-size: 30rpx;
}
.main .list {
  font-size: 13px;
  width: 100%;
}
.title {
  width: 100%;
  height: 60rpx;
  text-align: center;
}
.item {
  width: 100%;
  display: inline-block
}
.item .head {
  font-size: 16px;
  display: inline-block;
  padding: 15px 0;
  width: 80%;
}
.editAR {
  font-size: 16px;
  display: inline-block;
  padding: 15px 0;
  width: 20%;
  height:40px;
}
.item .h {
  width: 100%;
  height: 40px;
  line-height: 40px;
  display: inline-block;
}
.item .h .username {
  display:inline-block;
  color: #b3b3b3;
  font-size: 17px;
  margin-left: 15px;
}
.item .h .mobile {
  font-size: 16px;
  color: #b3b3b3;
  display:inline-block;
  margin-left:15px;
}
.item .head .b {
  width: 100%;
  padding-left:15px;
}
.item .operation {
  width:10%;
  height:70rpx;
  border-left:1rpx solid #eee;
  font-size:24rpx;
  text-align:right;
  margin-top:-15rpx;
  float:left;
  line-height:70rpx;
  color: #b3b3b3
}
.item radio {
  transform: scale(0.6);
}
.affirm {
  width: 540rpx;
  background: #ffffff;
  height: 340rpx;
  position: absolute;
  top: 0;
  z-index: 99;
  margin-left: calc(50% - 270rpx);
  margin-top: 50%;
  border-radius: 10rpx;
}
.affirm .btn {
  width: 250rpx;
  height: 70rpx;
  float: left;
  line-height: 70rpx;
  margin-left: 15rpx;
  color: #ffffff;
  font-size: 30rpx;
}
.affirm .title {
  width: 100%;
  height: 240rpx;
  text-align: center;
  line-height: 240rpx;
}
.affirm .cancel {
  background: #ffa200;
}
.affirm .confirm {
  background: #62b976;
}
::-webkit-scrollbar {
  width: 0;
  height: 0;
  color: transparent;
}
.news-bottom {
  max-width: 400rpx;
  height: 250rpx;
  margin: 3.125em auto;
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
}
.news-no {
  font-size: 28rpx;
  text-align: left;
  color: #999;
}
.submit {
  width: 712rpx;
  height: 80rpx;
  background: #62b976;
  border-radius: 10rpx;
  font-size: 32rpx;
  color: #ffffff;
}
.body {
  padding:.0 15px;
}
.main {
  width: 100%;
}
.list {
  width: calc(100% - 40rpx);
  height: 50px;
  line-height: 50px;
  background: #ffffff;
  border-top: 1px solid #f8f8f8;
  font-size: 13px;
}
radio {
  transform: scale(0.7);
}
.main {
  width:100%;
  /* height:calc(100vh - 130rpx); */
}
.vtag {
  font-size: 16px
}
.list .van-cell__title {
  font-size: 18rpx;
}
.demo-swipe-cell {
  -webkit-user-select: none;
          user-select: none;
}
.van-swipe-cell {
  color: #fff;
  font-size: 15px;
  width: 65px;
  height: 44px;
  display: inline-block;
  text-align: center;
  line-height: 44px;
  background-color: #f44;
}
</style>


